package com.yls.except.filter;

import com.yls.except.controller.UserController;
import com.yls.except.service.UserService;
import com.yls.except.util.*;
import com.yls.except.util.exception.ExceptionHandle;
import org.apache.log4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import javax.annotation.Resource;
import javax.servlet.*;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.Map;

/**
 * Created by xufan on 2017/8/4.
 */
@Component
public class WxLoginFilter extends ExceptionHandle implements Filter {

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
//        HttpServletRequest req = (HttpServletRequest) request;
//        HttpServletResponse resp = (HttpServletResponse) response;
//
//        UserService userService;
//        WebApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(req.getServletContext());
//        userService = (UserService) ac.getBean("userService");
//        req.setCharacterEncoding("UTF-8");
//        resp.setCharacterEncoding("UTF-8");
//        if (!isWechatbrowse(req))
//            chain.doFilter(req, resp);
////            GeneralResult.general(resp, null, 10006, 0); // 参数有误
//        else {
//            String token = "";
//            Cookie[] cookies = req.getCookies();
//            if (cookies != null) {
//                for (int i = 0; i < cookies.length; i++) {
//                    String name = cookies[i].getName();
//                    String value = cookies[i].getValue();
//                    if ("token".equals(name))
//                        token = value;
//                }
//            }
//            Logger log = Logger.getLogger(WxLoginFilter.class);
//            if (StringIsempty.isallempty(token)) {
//                String code = request.getParameter("code");
//                log.info("code=" + code);
//                if (code == null) {
//                    //重定向微信获取code
//                    String rurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ConstantUtil.APP_ID +
//                            "&redirect_uri=" + buildFullRequestUrl(req, code) + "&response_type=code"
//                            + "&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect";
//                    resp.sendRedirect(rurl);
//                    log.info("response1 =" + rurl);
//                    return;
//                } else {
//                    //通过code 获取openid
//                    Map map = WeiXinUtils.getMapByCode(code, ConstantUtil.APP_ID, ConstantUtil.APP_SECRET);
//                    if (map == null) {
//                        log.info("1url=" + buildFullRequestUrl(req, code));
//                        String u = buildFullRequestUrl(req, code);
//                        String rurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ConstantUtil.APP_ID +
//                                "&redirect_uri=" + u + "&response_type=code"
//                                + "&scope=snsapi_base&state=123&connect_redirect=1#wechat_redirect";
//                        log.info("response4 =" + rurl);
//                        resp.sendRedirect(rurl);
//                        return;
//                    }
//                    log.info("tokenmap:" + map);
//                    String opid = map.get("openid").toString();
//                    String access_token = map.get("access_token").toString();
//                    //查看数据库是否已经保存了该微信信息
//                    String src = ImgProperties.getimg("headimg");
//                    String realPath = req.getSession().getServletContext().getRealPath(src);
//                    Map<String, Object> wxuser = userService.updateUserByOpenid(opid, IpAddressUitls.getIpAddr(req), realPath);
//                    log.info("wxuser" + wxuser);
//                    if (wxuser == null) {
//                        //获取微信信息
//                        Map usermap = WeiXinUtils.getUserInfo(access_token, opid);
//                        log.info("usermap:" + usermap);
//                        if (usermap == null) {
//                            //无用户授权权限
//                            String rurl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + ConstantUtil.APP_ID +
//                                    "&redirect_uri=" + exceptCode(buildFullRequestUrl(req, code)) + "&response_type=code"
//                                    + "&scope=snsapi_userinfo&state=123&connect_redirect=1#wechat_redirect";
//                            log.info("response5 =" + rurl);
//                            resp.sendRedirect(rurl);
//                            return;
//                        } else {
//                            String friendopenid = request.getParameter("friendopenid") + "";
//                            wxuser = userService.insertUser(opid, dofilter(usermap.get("nickname") + ""), usermap.get("sex") + "", usermap.get("headimgurl") + "", IpAddressUitls.getIpAddr(req), friendopenid, realPath);
//                            log.info("wxuser" + wxuser);
//                        }
//                    }
//                    UserController.setUserCookie(resp, wxuser);
//                }
//            }
//            chain.doFilter(req, resp);
//        }
    }

    public boolean isWechatbrowse(HttpServletRequest req) {
        if (req.getHeader("user-agent") == null) {
            return true;
        }
        String ua = req.getHeader("user-agent").toLowerCase();
        if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
            return true;
        }
        return false;
    }

    public String exceptCode(String requestUrl) {
        int codeindex = requestUrl.indexOf("code=");
        if (codeindex > 0) {
            int next = requestUrl.indexOf("&", codeindex);
            if (next > 0) {
                String sub = requestUrl.substring(codeindex, next + 1);
                requestUrl = requestUrl.replace(sub, "");
            } else {
                requestUrl = requestUrl.substring(0, codeindex - 1);
            }
        }
        return requestUrl;
    }

    public static String buildFullRequestUrl(HttpServletRequest r, String code) {
//        String url = UrlUtils.buildFullRequestUrl(r.getScheme(), r.getServerName(), r.getServerPort(), r.getRequestURI(), r.getQueryString());
//        return url;
        String url = UrlUtils.buildFullRequestUrl(r.getScheme(), r.getServerName(), r.getServerPort(), r.getRequestURI(), r.getQueryString());
        Map<String, String[]> map = r.getParameterMap();
        org.slf4j.Logger log = LoggerFactory.getLogger(WxLoginFilter.class);
        url = url.replace("&code=" + code + "&state=123", "");
        try {
            if (StringIsempty.isNullMap(map)) {
                url += "?superaddition_type=0";
                return URLEncoder.encode(url, "UTF-8");
            } else {
                if (url.contains("superaddition_type=0"))
                    return URLEncoder.encode(url, "UTF-8");
                else if (url.contains("superaddition_type=1"))
                    return URLEncoder.encode(url, "UTF-8");
                else
                    url += "&superaddition_type=0";
                return URLEncoder.encode(url, "UTF-8");
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
            return null;
        }
    }


    public static String dofilter(String str) {
        String str_Result = "", str_OneStr = "";
        for (int z = 0; z < str.length(); z++) {
            str_OneStr = str.substring(z, z + 1);
            if (str_OneStr.matches("[\u4e00-\u9fa5]+") || str_OneStr.matches("[\\x00-\\x7F]+")) {
                str_Result = str_Result + str_OneStr;
            }
        }
        return str_Result.replaceAll("'", "").replaceAll("\"", "");
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
